const app = getApp()

Page({

  data: {
    movies: [
      { url: '../../static/l1x2.png', name: '绿茶', id: '2', img: "img_1" },
      { url: '../../static/hcx2.png', name: '红茶', id: '1', img: "img_2" },
      { url: '../../static/bx2.png', name: '白茶', id: '3', img: "img_3" },
      { url: '../../static/prx2.png', name: '普洱茶', id: '4', img: "img_4" },
      { url: '../../static/wlx2.png', name: '乌龙茶', id: '5', img: "img_5" },
      { url: '../../static/hx2.png', name: '黑茶', id: '6', img: "img_6" },
    ],
    botton: [],
    userInfo:[],
    block:'none',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },
  locationNumll404: function () {
    wx.navigateTo({
      url: '../Nullpage/Nullpage'
    })
  },
  locationlw: function () {
    wx.navigateTo({
      url: '../Contact/Contact'
    })
  },
  locationdesc: function () {
    wx.navigateTo({
      url: '../Description/Description'
    })
  },
  // 热门搜索跳转
  hot_search: function (e) {
    var e = e.target.dataset;
    if (!e.its_id) {
      var urls = '../Allot/Allot?id=' + e.bangdan_id + "&tid=" + e.teacase_id + '&hid=' + e.teaarea_id
    } else {
      if (e.bangdan_id == 1) {
        var urls = getApp().Craftsman +'?sid=' + e.its_id + '&id=' + e.bangdan_id + '&tid=' + e.teacase_id + '&hid=' + e.teaarea_id + "&ins=" + e.ins + '&biaozhi=1';
      } else if (e.bangdan_id == 2) {
        var urls = getApp().brand+'?sid=' + e.its_id + '&id=' + e.bangdan_id + '&tid=' + e.teacase_id + '&hid=' + e.teaarea_id + "&ins=" + e.ins + '&biaozhi=1';
      } else {
        var urls = getApp().Treasures +'?sid=' + e.its_id + '&id=' + e.bangdan_id + '&tid=' + e.teacase_id + '&hid=' + e.teaarea_id + "&ins=" + e.ins + '&biaozhi=1';
      }
    }
    // console.log(urls);
    wx.navigateTo({
      url: urls
    })
  },
  
  // 授权获取登录信息
  bindGetUserInfo: function (e) {
    // console.log("保存授权登录信息")
    // console.log(e.detail)
    if (e.detail.errMsg == 'getUserInfo:ok') {
      // 已授权
      app.wx_head = e.detail.userInfo.avatarUrl
      app.wx_nickname = e.detail.userInfo.nickname
      this.setData({
        userInfo: e.detail.userInfo,
        block: 'none'
      })
      this.sava_user(app.openid);
    }else{
      this.setData({
        userInfo: e.detail.userInfo,
        block: 'block'
      })
      // 未授权
    }
  },
  //保存信息or更新信息
  sava_user: function (openid){
    var that = this;
    var userInfo = this.data.userInfo;
    var scene = getApp().scene;
    wx.request({
      url: getApp().AppUrl + 'index.php/api/set/saveUserMessage',
      data: {
        openID: openid,
        nickName: userInfo.nickName,
        gender: userInfo.gender,
        city: userInfo.city,
        province: userInfo.province,
        country: userInfo.country,
        avatarUrl: userInfo.avatarUrl,
        scene: scene
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        // console.log(res)
        wx.hideLoading()
        if (res.data == "1") {
          that.setData({
            // 反馈成功将失去授权
            block: 'none',
          })
        } else {
          // 反馈没有一直授权
          block: 'blcok'
        }
      }
    })
  },
  //查看数据库是否存在openid的授权信息
  checkuser:function(openid){
    var that = this;
    // console.log("查询是否有openid字段")
    var userInfo = this.data.userInfo;
    wx.request({
      url: getApp().AppUrl + 'index.php/api/api/getUser',
      data: {
        openid: openid,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        // console.log(res)
        wx.hideLoading()
        if (res.data =="0"){
          that.setData({
            // 没信息将打开授权登录保存信息
            block: 'blcok'
          })
        }else{
          that.setData({
            // 有信息将更新登录信息
           block: 'none'
          })
          that.sava_user(openid)
        }
      }
    })
  },
  appopenids: function () {
   
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
      wx.getSystemInfo({
        success: function (res) {
          // console.log(res)
          that.setData({
            windowHeight: res.windowHeight,
            windowWidth: res.windowWidth,
          })
        }
      });
    wx.request({
      url: getApp().AppUrl + '/index.php/api/api/getTeaCase',
      data:{},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {

        // console.log(res.data)
      }
    })
    // 热门搜索
    wx.request({
      url: getApp().AppUrl + '/index.php/api/api/hot_search_ct',
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        // console.log(res.data);
        var datas = res.data;
        var strNum = 4;
        for (var c in datas) {
          var name = datas[c]['name'];
          if (name.length > strNum) {
            var name = name.substring(0, strNum);
          } else {
            datas[c]['name'] = name;
          }
        }
        
        that.setData({
          botton: datas
        })
      }
    })
    wx.getSetting({
      success: function (res) {
        var that = this;
        if (res.authSetting['scope.userInfo']) {
          // console.log('已经授权')
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              app.wx_head = res.userInfo.avatarUrl
              app.wx_nickname = res.userInfo.nickName
              // this.setData({
              //   userInfo: res.userInfo,
              // })
            }
          })
        } else {
          // console.log('未授权')
        }
      }
      // 调用失败
    })
    // 如果没有APPopenid 加载转动
    if (!app.openid) {
      wx.showLoading({
        title: '加载中',
      })
      wx.login({
        success: res => {
          var that = this;
          if (res.code) {
            wx.request({
              url: app.AppUrl + 'index.php/api/set/index',
              method: 'get',
              data: {
                code: res.code
              },
              success: function (e) {
                app.openid = e.data
                // console.log(e.data);
                that.checkuser(e.data)
                // wx.hideLoading()
              },
              fail: function (e) {
                var that = this;
                wx.login({
                  success: function (res) {
                    var code = res.code;
                    wx.getUserInfo({
                      success: function (res) {
                        wx.request({
                          url: app.AppUrl + 'index.php/api/set/index',
                          method: 'post',
                          data: {
                            code: code,
                          },
                          success: function (e) {
                            app.openid = e.data
                            that.checkuser(e.data)
                            // wx.hideLoading()
                          }
                        })
                      },
                      fail: function (res) {
                        // console.log(res)
                        wx.showModal({
                          title: '授权提示',
                          content: '小程序需要您的微信授权才能使用哦~ 错过授权页面的处理方法：删除小程序->重新搜索进入->点击授权按钮'
                        })
                      }
                    })
                  },
                  fail: function (res) {
                    // console.log(res)
                    wx.showModal({
                      title: '授权提示',
                      content: '小程序需要您的微信授权才能使用哦~ 错过授权页面的处理方法：删除小程序->重新搜索进入->点击授权按钮'
                    })
                  }
                });
              }
            })
          } else {
            console.log('获取用户登录态失败！' + res.errMsg)
          }
        },
        fail: function (res) {
          console.log(res)
        }
      })
    } else {
      this.checkuser(app.openid)
    }
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})